package com.ruoyi.demo.util;

import com.alibaba.dashscope.audio.asr.transcription.*;
import com.google.gson.*;
import org.springframework.stereotype.Component;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.net.HttpURLConnection;
import java.util.Arrays;
import java.util.List;

/**
 * @author 33692
 */
@Component
public class ParaformerUtil {
    /**
     * 调用 Paraformer 语音转文本 API
     *
     * @return 转换后的文本
     */
    public String speechToText(String audioFilePath) throws IOException {
        // 创建转写请求参数，需要用真实apikey替换your-dashscope-api-key
        TranscriptionParam param =
                TranscriptionParam.builder()
                        // 若没有将API Key配置到环境变量中，需将下面这行代码注释放开，并将apiKey替换为自己的API Key
                         .apiKey("sk-40a57798a0c7497f9be8034323984a94")
                        .model("paraformer-v1")
                        // “language_hints”只支持paraformer-v2和paraformer-realtime-v2模型
//                        .parameter("language_hints", new String[]{"zh", "en"})
                        .fileUrls(Arrays.asList(audioFilePath))
                        .build();
        try {
            Transcription transcription = new Transcription();
            // 提交转写请求
            TranscriptionResult result = transcription.asyncCall(param);
            // 等待转写完成
            System.out.println("RequestId: " + result.getRequestId());
            result = transcription.wait(
                    TranscriptionQueryParam.FromTranscriptionParam(param, result.getTaskId()));
            // 获取转写结果
            List<TranscriptionTaskResult> taskResultList = result.getResults();
            if (taskResultList != null && taskResultList.size() > 0) {
                StringBuilder transcriptionText = new StringBuilder();
                for (TranscriptionTaskResult taskResult : taskResultList) {
                    String transcriptionUrl = taskResult.getTranscriptionUrl();
                    HttpURLConnection connection =
                            (HttpURLConnection) new URL(transcriptionUrl).openConnection();
                    connection.setRequestMethod("GET");
                    connection.connect();
                    BufferedReader reader =
                            new BufferedReader(new InputStreamReader(connection.getInputStream()));
                    Gson gson = new GsonBuilder().setPrettyPrinting().create();
                    JsonObject jsonObject = gson.fromJson(reader, JsonObject.class);
//                    System.out.println("jsonObject"+jsonObject);
//                    System.out.println("ggson"+gson.toJson(jsonObject));

                    // 获取 transcripts 数组
                    JsonArray transcriptsArray = jsonObject.getAsJsonArray("transcripts");
//                    System.out.println("transcriptsArray "+transcriptsArray);
                    for (JsonElement element : transcriptsArray) {
                        JsonObject transcript = element.getAsJsonObject();
                        String text = transcript.get("text").getAsString();
                        System.out.println("提取的文本内容:\n" + text);
                        transcriptionText.append(text).append("\n");
                    }

                }
                return transcriptionText.toString(); // 返回转写结果
            }
        } catch (Exception e) {
            System.out.println("error: " + e);
        }
        return null; // 如果转写失败，返回 null
    }

}